package com.uzhie.web.aop;

import com.google.common.base.Strings;
import com.uzhie.web.bean.ErrorBean;
import com.uzhie.util.ValidateUtil;
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;

/**
 * Created by TangFei on 2018/7/14.
 */
public class ParamValidatorAspect {

    private Logger logger = Logger.getLogger(this.getClass());

    public <T> T around(ProceedingJoinPoint point) throws Throwable {
        logger.trace("进入 ParamValidatorAspect 环切");
        MethodSignature methodSignature = (MethodSignature) point.getSignature();
        Method method = methodSignature.getMethod();
        Object[] parameterValues = point.getArgs();
        String msg = ValidateUtil.validateOne(point.getTarget(), method, parameterValues);
        if (Strings.isNullOrEmpty(msg)) {
            // 参数校验通过
            return (T) point.proceed();
        } else {
            // 参数异常
            throw new IllegalArgumentException(msg) {
                public ErrorBean getError() {
                    ErrorBean errorBean = new ErrorBean();
                    errorBean.setCode(122);
                    errorBean.setMsg(getMessage());
                    return errorBean;
                }
            };
        }
    }

}
